<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>设备详情</span>
        <el-button type="primary" @click="goBack" plain>返回列表</el-button>
      </div>
    </template>

    <el-descriptions title="基本信息" border :column="2" v-loading="loading">
      <el-descriptions-item label="ID">{{ device.id || '-' }}</el-descriptions-item>
      <el-descriptions-item label="区域">{{ areaName }}</el-descriptions-item>
      <el-descriptions-item label="型号">{{ device.model || '-' }}</el-descriptions-item>
      <el-descriptions-item label="序列号">{{ device.serialNo || '-' }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="device.status === 'online' ? 'success' : 'danger'">
          {{ device.status === 'online' ? '在线' : '离线' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="最后心跳时间">{{ formatDate(device.lastHeartbeat) || '无记录' }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ formatDate(device.createdAt) || '-' }}</el-descriptions-item>
      <el-descriptions-item label="当前抄表读数(吨)">{{ device.currentMeterReading ? device.currentMeterReading.toFixed(2) : '0.00' }}</el-descriptions-item>
      <el-descriptions-item label="上月抄表读数(吨)">{{ device.lastMeterReading ? device.lastMeterReading.toFixed(2) : '0.00' }}</el-descriptions-item>
    </el-descriptions>

    <div style="margin-top: 30px;">
      <el-divider><el-icon><Monitor /></el-icon> 监控数据</el-divider>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header"><span>流量 (m³/h)</span></div>
            </template>
            <div id="flow-chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header"><span>压力 (MPa)</span></div>
            </template>
            <div id="pressure-chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header"><span>功率 (kW)</span></div>
            </template>
            <div id="power-chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import DeviceAPI from '@/api/system/device.api';
import AreaAPI from '@/api/system/area.api';
import { formatDate } from '@/utils/date';

const router = useRouter();
const route = useRoute();

const device = ref({});
const loading = ref(false);
const areaName = ref('-');

let flowInstance = null;
let pressureInstance = null;
let powerInstance = null;

const goBack = () => {
  router.push({ name: 'deviceList' });
};

const loadDevice = async () => {
  loading.value = true;
  try {
    const id = route.params.id;
    if (!id) return;
    const res = await DeviceAPI.getById(id);
    device.value = res;
    
    // 加载区域信息
    if (res.areaId) {
      await loadAreaInfo(res.areaId);
    }
    
    await loadDeviceData();
  } catch (error) {
    ElMessage.error('加载设备信息失败');
    console.error('加载设备信息失败:', error);
  } finally {
    loading.value = false;
  }
};

const loadAreaInfo = async (areaId) => {
  try {
    const area = await AreaAPI.getById(areaId);
    if (area && area.name) {
      areaName.value = area.name;
    }
  } catch (error) {
    console.error('加载区域信息失败:', error);
    areaName.value = '-';
  }
};

const loadDeviceData = async () => {
  try {
    const id = route.params.id;

    // 时间范围你可以按实际情况调整
    const startTime = '2024-06-15 09:00:00';
    const endTime   = '2024-06-15 15:00:00';

    const data = await DeviceAPI.getDeviceData(id, startTime, endTime);

    drawCharts(data);
  } catch (err) {
    ElMessage.error('加载监控数据失败');
    console.error("设备数据加载失败：", err);
  }
};

const drawCharts = (data) => {
  if (!Array.isArray(data) || data.length === 0) {
    ElMessage.warning("暂无监控数据");
    console.warn("返回的监控数据为空或格式错误", data);
    return;
  }

  const times = data.map(item => formatDate(item.timestamp, 'HH:mm'));
  const flowSeries = data.map(item => item.flow || 0);
  const pressureSeries = data.map(item => item.pressure || 0);
  const powerSeries = data.map(item => item.power || 0);

  flowInstance = echarts.init(document.getElementById("flow-chart"));
  pressureInstance = echarts.init(document.getElementById("pressure-chart"));
  powerInstance = echarts.init(document.getElementById("power-chart"));

  const baseOption = (title, data) => ({
    title: { text: title, left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [{
      type: 'line',
      data,
      smooth: true,
      symbol: 'circle'
    }]
  });

  flowInstance.setOption(baseOption("流量趋势", flowSeries));
  pressureInstance.setOption(baseOption("压力趋势", pressureSeries));
  powerInstance.setOption(baseOption("功率趋势", powerSeries));
};

const resizeCharts = () => {
  flowInstance?.resize();
  pressureInstance?.resize();
  powerInstance?.resize();
};

onMounted(() => {
  loadDevice();
  window.addEventListener('resize', resizeCharts);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  flowInstance?.dispose();
  pressureInstance?.dispose();
  powerInstance?.dispose();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
